package com.bookmngsys.service.impl;

import com.bookmngsys.dao.BookDao;
import com.bookmngsys.dao.BookInfoDao;
import com.bookmngsys.dao.ReaderDao;
import com.bookmngsys.dao.UserDao;
import com.bookmngsys.entity.Book;
import com.bookmngsys.entity.BookInfo;
import com.bookmngsys.entity.Reader;
import com.bookmngsys.entity.User;
import com.bookmngsys.service.UserService;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author han
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserDao userDao;

    @Autowired
    ReaderDao readerDao;

    @Autowired
    BookInfoDao bookInfoDao;

    @Override
    public User login(User user) {
        return userDao.findByUsernameAndPassword(user.getUsername(), user.getPassword());
    }

    @Override
    public boolean checkUserIsExist(String username) {
        return userDao.findByUsernameAndStatus(username,1) != null;
    }

    @Override
    public User getNormalUser(int id) {
        return userDao.getById(id);
    }

    @Override
    public boolean register(User user) {
        try {
            userDao.save(user);
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    public void updatePass(int id, String newPass) {
        User user = userDao.getById(id);
        user.setPassword(newPass);
        userDao.save(user);
    }

    @Override
    public void enableUser(int id) {
        userDao.updateUserStatus(id, 1);
    }

    @Override
    public void disableUser(int id) throws Exception {
        User user = new User();
        user.setId(id);
        List<BookInfo> BookAll = bookInfoDao.findAll();
        for(BookInfo bookInfo: BookAll){
            if(bookInfo.getReserveReaderId()!=null&&bookInfo.getReserveReaderId() == id){
                throw new Exception("the reader is borrowing book");
            }
            if(bookInfo.getBorrowReaderId()!=null&&bookInfo.getBorrowReaderId()==id){
                throw new Exception("the reader is borrowing book");
            }
        }
        List<Reader> readers = readerDao.findAll();
        for(Reader r:readers){
            if(r.getId() == user.getId()){
                readerDao.delete(r);
                break;
            }
        }
        userDao.delete(user);
    }
}
